/**
 * 
 */
package com.changil.nowonchangilchurch.protocol.http.widget;

import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.util.Log;
import android.widget.TextView;

import com.changil.nowonchangilchurch.util.UrlUtil;

/**
 * @author skplanet
 *
 */
public class HtmlSetter {
	
	private Context mContext;
	private TextView mHolder;
	private String mHtml;
	private AsyncImageGetter mImageGetter;
	
	private HashMap<String, Drawable> mImageMap = new HashMap<String, Drawable>();
	public HtmlSetter(Context context, TextView holder, String html) {
		mContext = context;
		mHolder = holder;
		mHtml = html;
		mImageGetter = new AsyncImageGetter();
	}
	
	private class AsyncImageGetter implements Html.ImageGetter {
		boolean isDownload;
		void setDownload(boolean down) {
			isDownload = down;
		}
		//Html.fromHtml에 의해 html 문자열이 해석될때 <img>태그를 만나면 무조건 호출..
		//그리고 최종 이함수에서 리턴하는 <img>태그에 출력
		//매개변수로 <img>태그의 src 속성값을 전달해준다
		@Override
		public Drawable getDrawable(String source) {
			final String thumb = UrlUtil.getThumbnailUrl(source, mContext.getResources().getDisplayMetrics().widthPixels);
			Drawable drawable = mImageMap.get(thumb);
			if (drawable != null) {
				drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
				return drawable;
			} else if (isDownload && drawable == null) {
				HttpImageCallback callback = new HttpImageCallback() {

					@Override
					public void onResult(Bitmap d) {
						Drawable drawable = null;
						drawable = new BitmapDrawable(mContext.getResources(), d);
						mImageMap.put(thumb, drawable);
						setTextViewHTML(false);
					}
				};
				HttpImageRequester requester = new HttpImageRequester();
				Log.e("zeropol2","썸네일은 "+thumb);
				requester.request(thumb, callback);
			}
			Log.d("kkang", "22222222222222");
			return null;
		}
	}
	
	
	
	public void setTextViewHTML(boolean down) {
		mImageGetter.setDownload(down);
		mHolder.setText(Html.fromHtml(mHtml,mImageGetter,null));	
	}

	
}
